/**
 * Created by guomin on 2017/5/4.
 */
var http=require('http');
var crypto=require('crypto');
var urlencode=require('urlencode');
var Promise=require('bluebird');
var rp=require('request-promise');
var qs=require('querystring');
var checkParams=require('../common/checkParams');
var client=require('../conf/redis');

client.on("error",function(err){
    console.log("Error",err);
});

var getCode=function(){
    var Num="";
    for(var i=0;i<6;i++){
        Num+=Math.floor(Math.random()*10);
    }
    return Num;
};

var sms={
    smsSend:function(req,params) {
        return new Promise(function (resolve, reject) {
            var mobile = params.mobile;
            checkParams.checkSameMobile(mobile,client).then(function(){
                var codeNum=getCode();
                var content = "感谢您参与微心愿手牵手活动，验证码" +codeNum+"，有效时间5分钟";
                console.log("content",content);
                var urlContent = urlencode(content);
                var re = /%20/g;
                var test=urlContent.toString();
                var encodeContent =test.replace(re, "+");
                var codestr = "e13d0basy67mox6" + mobile + encodeContent;
                var md5 = crypto.createHash('md5');
                md5.update(codestr);
                var code = md5.digest('hex');
                var postparams= {"appId": 6672, "content": encodeContent, "mobile": mobile, "code": code};
                var options={
                    uri:"http://sms.site.k618.cn",
                    method:"post",
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    },
                    body:qs.stringify(postparams)
                };
                rp(options).then(function(body){
                    var result=JSON.parse(body);
                    if(result.status==0){
                        client.set(mobile,"1");
                        client.expire(mobile,60);
                        client.set(mobile+"str",codeNum);
                        client.expire(mobile+"str",300);
                    }
                    resolve(result);
                }).catch(function(err){
                    reject(err);
                });
            }).catch(function(err){
                reject(err);
            });
        });
    }
};
exports=module.exports=sms;